package cn.pcios.kindle.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.pcios.kindle.action.KindleAction;
import cn.pcios.kindle.db.repository.MobiRepository;
import cn.pcios.kindle.db.table.Mobi;

@Service
public class EpubToMobiService {
	private static final Logger logger = LoggerFactory.getLogger(EpubToMobiService.class); 
	@Autowired
	private JavaMailSender mailSender;
	@Value("${config.FileHome}")
	private String FILEHOME;
	@Value("${config.KindlegenHome}")
	private String KINDLEGENHOME;
	@Value("${config.kindlemail}")
	private String kindlemail;
	@Value("${spring.mail.username}")
	private String myemail;
	@Autowired
	private MobiRepository mobiDao;

	 
	public int FileMiblieSendeMail(int epubid, String name)  {
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
		MimeMessage message = mailSender.createMimeMessage();
		simpleMailMessage.setTo(kindlemail);
		simpleMailMessage.setFrom(myemail);
		simpleMailMessage.setText(epubid+name+"起点书籍自动发送");
		simpleMailMessage.setSubject("主题："+name);
		
		try {
			
			MimeMessageHelper helper = new MimeMessageHelper(message, true);

			helper.setFrom(simpleMailMessage.getFrom());
			helper.setTo(simpleMailMessage.getTo());
			helper.setSubject(simpleMailMessage.getSubject());
			helper.setText(String.format(simpleMailMessage.getText(), kindlemail, name));
			FileSystemResource file = new FileSystemResource(epubid + ".mobi");
			helper.addAttachment(file.getFilename(), file);
			mailSender.send(message);
			return 1;
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		return 0;
	}
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public String FileEpubToMobi(int epubid, String name) throws IOException {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		Mobi ob = mobiDao.findById(epubid);
		if (ob != null) {

			logger.debug(ob.getId() + ",已存在");
			return "已存在";
		}
		if (new File(epubid + ".mobi").exists()) {
			new File(epubid + ".mobi").delete();
		}

		StringBuffer shell = new StringBuffer();
		if (KINDLEGENHOME == null || KINDLEGENHOME.equals("")) {
			shell.append("./kindlegen ");
		} else {
			shell.append(KINDLEGENHOME + "/kindlegen -locale zh ");
		}
		if (FILEHOME == null || FILEHOME.equals("")) {
			shell.append("./");
		} else {
			shell.append(FILEHOME + "/");
		}
		shell.append(epubid);
		shell.append(".epub");
		Process process = Runtime.getRuntime().exec(shell.toString());
		InputStream is = process.getInputStream();
		int r;
		while (-1 != ( r= is.read())) {
			//System.out.print((char) r);
		}
		
		if ( new File(epubid + ".mobi").exists()) {
			Mobi newobj = new Mobi();
			newobj.setId(epubid);
			newobj.setFile(epubid + ".mobi");
			newobj.setName(name);
			newobj.setSend(0);
			mobiDao.save(newobj);
			
			return "成功";
		} else {
			
			return "失败";
		}

	}

}
